package org.ediba.siri.core.action.data;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.ediba.siri.core.Filter;
import org.ediba.siri.core.action.data.ActionGrantDao;
import org.ediba.siri.core.action.domain.ActionGrant;
import org.ediba.siri.core.common.data.HibernateDomainDao;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;

public class HibernateActionGrantDao extends HibernateDomainDao<ActionGrant, Integer> implements ActionGrantDao {
	
	public HibernateActionGrantDao(){super(ActionGrant.class);}
	
	protected DetachedCriteria buildCriteria(Map<Filter,Collection<Object>> filters){
		DetachedCriteria detachedCriteria = this.buildCriteria();
		Disjunction or;
		Conjunction and = Restrictions.conjunction();
		
		for (Map.Entry<Filter,Collection<Object>> filter : filters.entrySet()){
			or = Restrictions.disjunction();			
			for (Object value : filter.getValue()) 
				switch (filter.getKey()) {
				case ACTIONREQUEST_USER:    detachedCriteria.createAlias("actionrequest", "actionrequest");
											detachedCriteria.createAlias("actionrequest.user", "actionrequestuser");
											if (value == null)
												or.add(Restrictions.isNull("actionrequestuser"));
											else 
												or.add(Restrictions.eq("actionrequestuser.id", value));
											break;
				case IMAGE:			if (value == null)
										or.add(Restrictions.isNull(filter.getKey().getProperty()));
									else 
										or.add(Restrictions.eq(filter.getKey().getPropertyId(), value));
				}
			and.add(or);
		}
			
		detachedCriteria.add(and);
		
		return detachedCriteria;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ActionGrant> findOpen(Integer idImage, Integer idRequestUser) {
		String _hql = "";
		
		_hql += "from org.ediba.siri.core.action.domain.ActionGrant ag where";
		_hql += "     ag.actiondownload is empty";
		_hql += " and ag.actionfinish is empty";
		if (idImage != null)
		_hql += " and ag.image.id = " + idImage.toString();
		if (idRequestUser != null)
		_hql += " and ag.actionrequest.user.id = " + idRequestUser.toString();
		
		return (List<ActionGrant>) this.getHibernateTemplate().find(_hql);
	}
	
}
